﻿@inject ISettingsService _settingsService
@inject IStorageService _storageService
@inject ChatState _chatState
@inject ISnackbar Snackbar

@implements IDisposable

<EditForm Model="@AppSettings" OnValidSubmit="OnValidSubmit">
    <DataAnnotationsValidator />
    <div class="d-flex flex-column flex-grow-1 gap-3">
        <MudText>Name</MudText>
        <MudTextField @bind-Value="AppSettings.Profile!.Name" Variant="Variant.Outlined" Margin="Margin.Dense" HelperText="How should the Assistant address you?"/>

        <MudText>Avatar</MudText>
        <AvatarUpload ImageUrl="@AppSettings.Profile.AvatarUrl" OnInputFileChanged="OnInputFileChanged" />

        <MudText>Custom instructions</MudText>
        <div>
            <MudTextField @bind-Value="AppSettings.Profile.Description"
                          T="string" 
                          Variant="Variant.Outlined"
                          AutoGrow
                          Lines="7"
                          MaxLines="10"
                          Margin="Margin.Dense" />
             <div class="px-2">
                <MudText Typo="Typo.caption" Class="mt-0" Style="color: var(--mud-palette-text-secondary); font-size: .75rem; text-align: start; font-weight: 400; line-height: 1.66; letter-spacing: .03333em;">
                    @((MarkupString)descriptionGuidelines)
                </MudText>
             </div>

        </div>

    </div>
    <div class="d-flex flex-row flex-grow-1 justify-end gap-4 pa-4">
        <MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto">Save</MudButton>
    </div>
</EditForm>

@code 
{
    private AppSettingsResponse AppSettings { get; set; } = new();
    private bool success;

    private const string descriptionGuidelines = @"
        Provide any details you’d like the Assistant to consider in responses.<br />These custom instructions will be included in all new conversations.<br /><br />Here are some suggestions:<br />
        - Projects: Describe current or upcoming projects.<br />
        - Personal Info: Share relevant details about yourself.<br />
        - Occupation: Mention your job or field of work.<br />
        - Preferences: Specify any particular interests or preferences.<br />
        - Goals: Outline your short-term or long-term goals.<br /><br />
        Feel free to include anything else that will help the Assistant better understand and assist you.<br /><br />
        <strong>⚠️ Please avoid sharing sensitive information.</strong>";

    protected async override Task OnInitializedAsync()
    {
        _chatState.UserNameChanged += StateHasChanged;
        _chatState.UserAvatarChanged += StateHasChanged;

        await PopulateForm();
    }

    private async Task PopulateForm()
    {
        var response = await _settingsService.GetSettingsAsync();
        var settings = response.Value;

        if(settings is not null)
        {
            AppSettings = settings;

            _chatState.SetUserName(settings.Profile.Name);
            _chatState.SetUserAvatar(settings.Profile.AvatarUrl);
        }
    }

    private async Task OnValidSubmit(EditContext context)
    {
        await UpdateProfileAsync(AppSettings);
        StateHasChanged();
    }

    private async Task UpdateProfileAsync(AppSettingsResponse appSettings)
    {
        if (appSettings is not null)
        {
            var response = await _settingsService.UpdateProfileAsync(
                appSettings.Profile.Name, 
                appSettings.Profile.AvatarUrl, 
                appSettings.Profile.Description);

            if (!response.Succeeded)
            {
                ShowErrorSnackbar("Failed to update profile. Please try again.", Severity.Error);
            }

            _chatState.SetUserName(appSettings.Profile.Name);
            _chatState.SetUserAvatar(appSettings.Profile.AvatarUrl);

            ShowErrorSnackbar("Profile updated successfully!", Severity.Success);
            success = true;
        }
    }

    private async Task OnInputFileChanged(InputFileChangeEventArgs e)
    {
        var file = e.File;

        if(file is not null)
        {
            var response = await _storageService.UploadFileAsync(file, "avatar");
            AppSettings.Profile.AvatarUrl = response.Url;
        }
    }

    private void ShowErrorSnackbar(string message, Severity severity)
    {
        Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopRight;

        Snackbar.Add(message, severity, options =>
        {
            options.HideTransitionDuration = 100;
        });
    }

    public void Dispose()
    {
        _chatState.UserNameChanged -= StateHasChanged;
        _chatState.UserAvatarChanged -= StateHasChanged;
    }
}
